package com.west.xu.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.west.xu.sms.config.Constant;
import com.west.xu.sms.config.SmsConfig;
import com.west.xu.sms.domain.SmsEntity;
import com.west.xu.sms.domain.SmsMessage;
import com.west.xu.sms.service.ISmsService;
import com.west.xu.sms.util.SendSmsUtil;
import com.west.xu.sms.util.SignUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class SmsServiceImpl implements ISmsService {

    @Autowired
    SmsConfig smsConfig;

    @Override
    public String sendSms(SmsMessage smsMessage) throws IOException {
        SmsEntity smsEntity = new SmsEntity();
        smsEntity.setMobile(smsMessage.getMobile());
        smsEntity.setContent(smsMessage.getContent());
        smsEntity.setSerialNo(RandomStringUtils.randomAlphabetic(20));
        smsEntity.setTemplateId(smsConfig.getTemplateId());

        JSONObject requestJson = JSONObject.parseObject(JSONObject.toJSONString(smsEntity));
        String sign = getSign(requestJson);
        requestJson.put(Constant.SIGN_KEY, sign);
//        System.out.println(requestJson.toJSONString());
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put(Constant.CONTENT_TYPE_KEY, MediaType.APPLICATION_STREAM_JSON.toString());
        headerMap.put(Constant.AUTHORIZATION_KEY, smsConfig.getAuthorization());
        return SendSmsUtil.sendPost(smsConfig.getUrl(), requestJson.toJSONString(), headerMap);
    }

    private String getSign(JSONObject jsonObject) {
        List<String> list = new ArrayList<>();
        Set<String> keySet = jsonObject.keySet();
        //将参数按照ASCII码表的正序排序
        for (String str : keySet) {
            if (Constant.SIGN_KEY.equals(str)) {
                continue;
            }
            list.add(str);
        }
        list.sort(String.CASE_INSENSITIVE_ORDER);
        //将排好序的字段名称和字段值拼接为字符串
        StringBuilder sb = new StringBuilder();
        list.forEach(s -> {
            sb.append(s);
            sb.append(jsonObject.getString(s));
        });
        //将字符串转换为小写
        String str = sb.toString().toLowerCase();
        //根据提供的私钥对拼接好的字符串数据进行加密
        String signKey = SignUtils.getSignKey(smsConfig.getPrivateKey(), null, str, smsConfig.getAlgorithm());
        return signKey;
    }
}
